﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using Dasic.Library;
using Dasic.Model;
using Dos.ORM;
using MySql.Data.MySqlClient;

namespace Dasic.Controls
{
    /// <summary>
    ///     DbCompare.xaml 的交互逻辑
    /// </summary>
    public partial class DbCompare : Window
    {
        private DbSession _mainDbSession;
        private DbSession _slaveDbSession;

        public DbCompare()
        {
            InitializeComponent();
        }

        /// <summary>
        ///     弹出设置窗口
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BtnSetting_OnClick(object sender, RoutedEventArgs e)
        {
            var dbCompareSet = new DbCompareSet();
            dbCompareSet.ShowDialog();
        }

        /// <summary>
        ///     连接数据库，并列出所有表
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void BtnConnection_OnClick(object sender, RoutedEventArgs e)
        {
            Loading(true);
            try
            {
                var rsDbComparse = await GetSqLiteData();
                if (rsDbComparse == null)
                {
                    Loading(false);
                    Common.Msg(false, "请先配置数据库信息！");
                    BtnSetting_OnClick(sender, e);
                    return;
                }
                LabelLeft.Content = $"IP:{rsDbComparse.mip}    表:{rsDbComparse.mtable}";
                LabelRight.Content = $"IP:{rsDbComparse.sip}    表:{rsDbComparse.stable}";
                //获取主库的连接对象
                var mainConnectionStr = Common.ConnectionStr(rsDbComparse.mip, rsDbComparse.mport, rsDbComparse.muser,
                    rsDbComparse.mpass, rsDbComparse.mtable);
                _mainDbSession = SqlHelper.MySqlConnection(mainConnectionStr);
                //获取副库的连接对象
                var slaveConnectionStr = Common.ConnectionStr(rsDbComparse.sip, rsDbComparse.sport, rsDbComparse.suser,
                    rsDbComparse.spass, rsDbComparse.stable);
                _slaveDbSession = SqlHelper.MySqlConnection(slaveConnectionStr);
                //开始绑定树
                var rs = await BindTreeView(TreeViewMain, TreeViewSlave, _mainDbSession, _slaveDbSession, "");
                if (rs)
                    Loading(false);
            }
            catch (Exception ex)
            {
                Loading(false);
                Common.Msg(false, $"出现意想不到的错误，信息：{ex.Message}");
            }
        }

        private static async Task<SQLiteDbComparse> GetSqLiteData()
        {
            return await Task.Run(() => SqlHelper.SqLiteConnection.From<SQLiteDbComparse>().ToFirst());
        }

        /// <summary>
        ///     绑定树
        /// </summary>
        /// <param name="mainTreeView">主表树</param>
        /// <param name="slaveTreeView">副表树</param>
        /// <param name="mainDbSession">主表数据库对象</param>
        /// <param name="slaveDbSession">副表数据库对象</param>
        /// <returns></returns>
        private async Task<bool> BindTreeView(ItemsControl mainTreeView, ItemsControl slaveTreeView,
            DbSession mainDbSession, DbSession slaveDbSession, string tableName)
        {
            //绑定之前先清空一下树
            mainTreeView.Items.Clear();
            slaveTreeView.Items.Clear();
            var mainDict = await GetTableFields(mainDbSession);
            var slaveDict = await GetTableFields(slaveDbSession);
            await
                ParseHash(mainDict, slaveDict, mainTreeView, slaveTreeView, mainDbSession, slaveDbSession, 1, tableName);
            await
                ParseHash(slaveDict, mainDict, slaveTreeView, mainTreeView, slaveDbSession, mainDbSession, 2, tableName);
            return true;
        }


        /// <summary>
        ///     解析数据并绑定到树上
        /// </summary>
        /// <param name="mainDict">主表字典</param>
        /// <param name="slaveDict">副表字典</param>
        /// <param name="mainTreeView">主表树</param>
        /// <param name="slaveTreeView">副表树</param>
        /// <param name="mainDbSession">主表数据库对象</param>
        /// <param name="slaveDbSession">副表数据库对象</param>
        /// <param name="pos">1=在左边，2=在右边</param>
        /// <param name="tableName"></param>
        /// <returns></returns>
        private async Task<bool> ParseHash(
            IReadOnlyDictionary<string, Dictionary<string, Dictionary<string, string>>> mainDict,
            IReadOnlyDictionary<string, Dictionary<string, Dictionary<string, string>>> slaveDict,
            ItemsControl mainTreeView, ItemsControl slaveTreeView, DbSession mainDbSession, DbSession slaveDbSession,
            int pos, string tableName)
        {
            return await Task.Run(() =>
            {
                Dispatcher.BeginInvoke(new Action(() =>
                {
                    var newDictTableKeys = mainDict.Keys.Union(slaveDict.Keys).ToList();
                    newDictTableKeys.Sort();
                    foreach (var dictTableKey in newDictTableKeys)
                    {
                        bool notChiltDiff; //子节点正常
                        //如果两边都有该表
                        var notDiff = mainDict.ContainsKey(dictTableKey) && slaveDict.ContainsKey(dictTableKey);
                        //生成父节点
                        var viewTreeParentItem = new TreeViewParent
                        {
                            Header = dictTableKey,
                            Tag = dictTableKey,
                            IcoImage = new BitmapImage(new Uri("../Images/ico_db1.png", UriKind.RelativeOrAbsolute)),
                            ExpandImage =
                                new BitmapImage(new Uri("../Images/folder_2.png", UriKind.RelativeOrAbsolute)),
                            Margin = new Thickness(1),
                            Padding = new Thickness(4),
                            Visibility = mainDict.ContainsKey(dictTableKey) ? Visibility.Visible : Visibility.Hidden,
                            ContextMenu = ContextMenuParent(mainDbSession, slaveDbSession, pos, dictTableKey, notDiff)
                        };
                        if (dictTableKey == tableName)
                        {
                            viewTreeParentItem.IsExpanded = true;
                            viewTreeParentItem.IsSelected = true;
                        }
                        viewTreeParentItem.SetResourceReference(TemplateProperty, "TreeViewParentTpl");
                        //添加子节点头
                        var viewTreeChildHead = new TreeViewItem();
                        viewTreeChildHead.SetResourceReference(TemplateProperty, "TreeViewChildHeader");
                        viewTreeParentItem.Items.Add(viewTreeChildHead);
                        //如果两边都有该表
                        if (notDiff)
                        {
                            notChiltDiff = ParseHashBindViewTree(mainDict, slaveDict, mainDbSession, slaveDbSession,
                                viewTreeParentItem, dictTableKey, pos, true);
                        }
                        else
                        {
                            notChiltDiff = false;
                            //如果只是左边有
                            if (mainDict.ContainsKey(dictTableKey))
                                foreach (var dictFieldKey in mainDict[dictTableKey].Keys)
                                {
                                    var viewTreeChildItem = new TreeViewChild
                                    {
                                        StrField = dictFieldKey,
                                        StrColl = mainDict[dictTableKey][dictFieldKey]["Collation"],
                                        StrType = mainDict[dictTableKey][dictFieldKey]["Type"],
                                        StrNull = mainDict[dictTableKey][dictFieldKey]["Null"],
                                        StrKey = mainDict[dictTableKey][dictFieldKey]["Key"],
                                        StrDefault = mainDict[dictTableKey][dictFieldKey]["Default"],
                                        StrExtra = mainDict[dictTableKey][dictFieldKey]["Extra"],
                                        StrComment = mainDict[dictTableKey][dictFieldKey]["Comment"],
                                        ContextMenu = ContextMenuChild(mainDbSession, slaveDbSession, pos,
                                            dictTableKey, dictFieldKey, false, false)
                                    };
                                    viewTreeChildItem.PreviewMouseRightButtonUp += (sender, args) =>
                                    {
                                        var i = (TreeViewItem) sender;
                                        if (i != null) i.IsSelected = true;
                                    };
                                    SetFontColor(viewTreeChildItem);
                                    viewTreeChildItem.SetResourceReference(TemplateProperty, "TreeViewChildTpl");
                                    viewTreeParentItem.Items.Add(viewTreeChildItem);
                                }
                            //如果只是右边有
                            if (slaveDict.ContainsKey(dictTableKey))
                                foreach (var dictFieldKey in slaveDict[dictTableKey].Keys)
                                {
                                    var viewTreeChildItem = new TreeViewChild
                                    {
                                        StrField = dictFieldKey,
                                        StrFieldColor = new SolidColorBrush(Color.FromRgb(245, 245, 245)),
                                        StrColl = slaveDict[dictTableKey][dictFieldKey]["Collation"],
                                        StrCollColor = new SolidColorBrush(Color.FromRgb(245, 245, 245)),
                                        StrType = slaveDict[dictTableKey][dictFieldKey]["Type"],
                                        StrTypeColor = new SolidColorBrush(Color.FromRgb(245, 245, 245)),
                                        StrNull = slaveDict[dictTableKey][dictFieldKey]["Null"],
                                        StrNullColor = new SolidColorBrush(Color.FromRgb(245, 245, 245)),
                                        StrKey = slaveDict[dictTableKey][dictFieldKey]["Key"],
                                        StrKeyColor = new SolidColorBrush(Color.FromRgb(245, 245, 245)),
                                        StrDefault = slaveDict[dictTableKey][dictFieldKey]["Default"],
                                        StrDefaultColor = new SolidColorBrush(Color.FromRgb(245, 245, 245)),
                                        StrExtra = slaveDict[dictTableKey][dictFieldKey]["Extra"],
                                        StrExtraColor = new SolidColorBrush(Color.FromRgb(245, 245, 245)),
                                        StrComment = slaveDict[dictTableKey][dictFieldKey]["Comment"],
                                        StrCommentColor = new SolidColorBrush(Color.FromRgb(245, 245, 245)),
                                        IsEnabled = false
                                    };
                                    viewTreeChildItem.SetResourceReference(TemplateProperty, "TreeViewChildTpl");
                                    viewTreeParentItem.Items.Add(viewTreeChildItem);
                                }
                        }
                        //添加子节点底
                        var viewTreeChildFood = new TreeViewItem();
                        viewTreeChildFood.SetResourceReference(TemplateProperty, "TreeViewFoodTpl");
                        viewTreeParentItem.Items.Add(viewTreeChildFood);
                        //如果子节点有异常
                        if (!notChiltDiff)
                            viewTreeParentItem.Foreground = new SolidColorBrush(Color.FromRgb(255, 69, 0));
                        //鼠标右键时选中
                        viewTreeParentItem.PreviewMouseRightButtonUp += (sender, args) =>
                        {
                            var mainItem = (TreeViewItem)sender;
                            if (mainItem == null) return;
                            mainItem.IsSelected = true;
                            foreach (TreeViewItem item in slaveTreeView.Items)
                            {
                                var dObject =
                                    slaveTreeView.ItemContainerGenerator.ContainerFromItem(item) as TreeViewItem;
                                if ((dObject != null) && !dObject.IsExpanded &&
                                    (dObject.Tag.ToString() == mainItem.Tag.ToString()))
                                    dObject.IsSelected = true;
                            }
                        };
                        //展开节点时
                        viewTreeParentItem.Expanded += (sender, args) =>
                        {
                            var mainItem = (TreeViewItem) sender;
                            foreach (TreeViewItem item in slaveTreeView.Items)
                            {
                                var dObject =
                                    slaveTreeView.ItemContainerGenerator.ContainerFromItem(item) as TreeViewItem;
                                if ((dObject != null) && !dObject.IsExpanded &&
                                    (dObject.Tag.ToString() == mainItem.Tag.ToString()))
                                    dObject.IsExpanded = true;
                            }
                        };
                        viewTreeParentItem.Collapsed += (sender, args) =>
                        {
                            var mainItem = (TreeViewItem) sender;
                            foreach (TreeViewItem item in slaveTreeView.Items)
                            {
                                var dObject =
                                    slaveTreeView.ItemContainerGenerator.ContainerFromItem(item) as TreeViewItem;
                                if ((dObject != null) && dObject.IsExpanded &&
                                    (dObject.Tag.ToString() == mainItem.Tag.ToString()))
                                    dObject.IsExpanded = false;
                            }
                        };
                        //加子节点添加到父节点中
                        mainTreeView.Items.Add(viewTreeParentItem);
                    }
                }));
                return true;
            });
        }


        private bool ParseHashBindViewTree(
            IReadOnlyDictionary<string, Dictionary<string, Dictionary<string, string>>> mainDict,
            IReadOnlyDictionary<string, Dictionary<string, Dictionary<string, string>>> slaveDict,
            DbSession mainDbSession, DbSession slaveDbSession,
            ItemsControl viewTreeParentItem, string dictTableKey, int pos, bool notDiff)
        {
            var isChildHave = true;
            var newDictFieldKeys = mainDict[dictTableKey].Keys.Union(slaveDict[dictTableKey].Keys).ToList();
            //newDictFieldKeys.Sort();
            foreach (var dictFieldKey in newDictFieldKeys)
                if (mainDict[dictTableKey].ContainsKey(dictFieldKey))
                {
                    var mainColl = mainDict[dictTableKey][dictFieldKey]["Collation"];
                    var mainType = mainDict[dictTableKey][dictFieldKey]["Type"];
                    var mainNull = mainDict[dictTableKey][dictFieldKey]["Null"];
                    var mainKey = mainDict[dictTableKey][dictFieldKey]["Key"];
                    var mainDefault = mainDict[dictTableKey][dictFieldKey]["Default"];
                    var mainExtra = mainDict[dictTableKey][dictFieldKey]["Extra"];
                    var mainComment = mainDict[dictTableKey][dictFieldKey]["Comment"];
                    var viewTreeChildItem = new TreeViewChild
                    {
                        StrField = dictFieldKey,
                        StrColl = mainColl,
                        StrType = mainType,
                        StrNull = mainNull,
                        StrKey = mainKey,
                        StrDefault = mainDefault,
                        StrExtra = mainExtra,
                        StrComment = mainComment,
                        ContextMenu = ContextMenuChild(mainDbSession, slaveDbSession, pos,
                            dictTableKey, dictFieldKey, true, notDiff)
                    };
                    //鼠标右键时选中
                    viewTreeChildItem.PreviewMouseRightButtonUp += (sender, args) =>
                    {
                        var i = (TreeViewItem) sender;
                        if (i != null) i.IsSelected = true;
                    };
                    //如果左边有，右边没有，则标红
                    if (!slaveDict[dictTableKey].ContainsKey(dictFieldKey))
                    {
                        isChildHave = false;
                        viewTreeChildItem.ContextMenu = ContextMenuChild(mainDbSession, slaveDbSession, pos,
                            dictTableKey, dictFieldKey, false, notDiff);
                        SetFontColor(viewTreeChildItem);
                    }
                    else //如果右边也有，则判断各字段值是否相同
                    {
                        var slaveColl = slaveDict[dictTableKey][dictFieldKey]["Collation"];
                        if (mainColl != slaveColl)
                        {
                            isChildHave = false;
                            viewTreeChildItem.ContextMenu = ContextMenuChild(mainDbSession, slaveDbSession, pos,
                                dictTableKey, dictFieldKey, false, notDiff);
                            viewTreeChildItem.StrCollColor = new SolidColorBrush(Color.FromRgb(255, 69, 0));
                        }
                        var slaveType = slaveDict[dictTableKey][dictFieldKey]["Type"];
                        if (mainType != slaveType)
                        {
                            isChildHave = false;
                            viewTreeChildItem.ContextMenu = ContextMenuChild(mainDbSession, slaveDbSession, pos,
                                dictTableKey, dictFieldKey, false, notDiff);
                            viewTreeChildItem.StrTypeColor = new SolidColorBrush(Color.FromRgb(255, 69, 0));
                        }
                        var slaveNull = slaveDict[dictTableKey][dictFieldKey]["Null"];
                        if (mainNull != slaveNull)
                        {
                            isChildHave = false;
                            viewTreeChildItem.ContextMenu = ContextMenuChild(mainDbSession, slaveDbSession, pos,
                                dictTableKey, dictFieldKey, false, notDiff);
                            viewTreeChildItem.StrNullColor = new SolidColorBrush(Color.FromRgb(255, 69, 0));
                        }
                        var slaveKey = slaveDict[dictTableKey][dictFieldKey]["Key"];
                        if (mainKey != slaveKey)
                        {
                            isChildHave = false;
                            viewTreeChildItem.ContextMenu = ContextMenuChild(mainDbSession, slaveDbSession, pos,
                                dictTableKey, dictFieldKey, false, notDiff);
                            viewTreeChildItem.StrKeyColor = new SolidColorBrush(Color.FromRgb(255, 69, 0));
                        }
                        var slaveDefault = slaveDict[dictTableKey][dictFieldKey]["Default"];
                        if (mainDefault != slaveDefault)
                        {
                            isChildHave = false;
                            viewTreeChildItem.ContextMenu = ContextMenuChild(mainDbSession, slaveDbSession, pos,
                                dictTableKey, dictFieldKey, false, notDiff);
                            viewTreeChildItem.StrDefaultColor = new SolidColorBrush(Color.FromRgb(255, 69, 0));
                        }
                        var slaveExtra = slaveDict[dictTableKey][dictFieldKey]["Extra"];
                        if (mainExtra != slaveExtra)
                        {
                            isChildHave = false;
                            viewTreeChildItem.ContextMenu = ContextMenuChild(mainDbSession, slaveDbSession, pos,
                                dictTableKey, dictFieldKey, false, notDiff);
                            viewTreeChildItem.StrExtraColor = new SolidColorBrush(Color.FromRgb(255, 69, 0));
                        }
                        var slaveComment = slaveDict[dictTableKey][dictFieldKey]["Comment"];
                        if (mainComment != slaveComment)
                        {
                            isChildHave = false;
                            viewTreeChildItem.ContextMenu = ContextMenuChild(mainDbSession, slaveDbSession, pos,
                                dictTableKey, dictFieldKey, false, notDiff);
                            viewTreeChildItem.StrCommentColor = new SolidColorBrush(Color.FromRgb(255, 69, 0));
                        }
                    }
                    viewTreeChildItem.SetResourceReference(TemplateProperty, "TreeViewChildTpl");
                    viewTreeParentItem.Items.Add(viewTreeChildItem);
                }
                else //如果没有，则从右边找，并设置为不显示
                {
                    isChildHave = false;
                    var viewTreeChildItem = new TreeViewChild
                    {
                        StrField = dictFieldKey,
                        StrFieldColor = new SolidColorBrush(Color.FromRgb(245, 245, 245)),
                        StrColl = slaveDict[dictTableKey][dictFieldKey]["Collation"],
                        StrCollColor = new SolidColorBrush(Color.FromRgb(245, 245, 245)),
                        StrType = slaveDict[dictTableKey][dictFieldKey]["Type"],
                        StrTypeColor = new SolidColorBrush(Color.FromRgb(245, 245, 245)),
                        StrNull = slaveDict[dictTableKey][dictFieldKey]["Null"],
                        StrNullColor = new SolidColorBrush(Color.FromRgb(245, 245, 245)),
                        StrKey = slaveDict[dictTableKey][dictFieldKey]["Key"],
                        StrKeyColor = new SolidColorBrush(Color.FromRgb(245, 245, 245)),
                        StrDefault = slaveDict[dictTableKey][dictFieldKey]["Default"],
                        StrDefaultColor = new SolidColorBrush(Color.FromRgb(245, 245, 245)),
                        StrExtra = slaveDict[dictTableKey][dictFieldKey]["Extra"],
                        StrExtraColor = new SolidColorBrush(Color.FromRgb(245, 245, 245)),
                        StrComment = slaveDict[dictTableKey][dictFieldKey]["Comment"],
                        StrCommentColor = new SolidColorBrush(Color.FromRgb(245, 245, 245)),
                        IsEnabled = false
                    };
                    viewTreeChildItem.SetResourceReference(TemplateProperty, "TreeViewChildTpl");
                    viewTreeParentItem.Items.Add(viewTreeChildItem);
                }
            return isChildHave;
        }


        /// <summary>
        ///     获取数据库字段信息
        /// </summary>
        /// <param name="dbSession">数据库连接对象</param>
        /// <returns></returns>
        private static async Task<Dictionary<string, Dictionary<string, Dictionary<string, string>>>> GetTableFields(
            DbSession dbSession)
        {
            return await Task.Run(() =>
            {
                var dictTables = new Dictionary<string, Dictionary<string, Dictionary<string, string>>>();
                //获取各表信息
                var rsTables = dbSession.FromSql("SHOW TABLES").ToDataTable();
                foreach (DataRow dataRow in rsTables.Rows)
                {
                    var field = dataRow[0].ToString();
                    var rsFields = dbSession.FromSql($"SHOW FULL FIELDS FROM `{field}`").ToDataTable();
                    var dictFields = rsFields.Rows.Cast<DataRow>()
                        .ToDictionary(row => row["Field"].ToString(), row => new Dictionary<string, string>
                        {
                            {"Field", row["Field"].ToString()},
                            {"Collation", row["Collation"].ToString()},
                            {"Type", row["Type"].ToString()},
                            {"Null", row["Null"].ToString()},
                            {"Key", row["Key"].ToString()},
                            {"Default", row["Default"].ToString()},
                            {"Extra", row["Extra"].ToString()},
                            {"Comment", row["Comment"].ToString()}
                        });
                    dictTables.Add(field, dictFields);
                }
                return dictTables;
            });
        }

        /// <summary>
        ///     鼠标滚轮滚动
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ScrollViewerMouseWheel(object sender, MouseWheelEventArgs e)
        {
            var viewer = (ScrollViewer) sender;
            double num = Math.Abs(e.Delta/2);
            var offset = e.Delta > 0
                ? Math.Max(0.0, viewer.VerticalOffset - num)
                : Math.Min(viewer.ScrollableHeight, viewer.VerticalOffset + num);
            if (Math.Abs(offset - viewer.VerticalOffset) < 1) return;
            viewer.ScrollToVerticalOffset(offset);
            e.Handled = true;
        }


        /// <summary>
        ///     设置字段为红色
        /// </summary>
        /// <param name="viewTreeChildItem"></param>
        private static void SetFontColor(TreeViewChild viewTreeChildItem)
        {
            viewTreeChildItem.StrFieldColor = new SolidColorBrush(Color.FromRgb(255, 69, 0));
            viewTreeChildItem.StrCollColor = new SolidColorBrush(Color.FromRgb(255, 69, 0));
            viewTreeChildItem.StrTypeColor = new SolidColorBrush(Color.FromRgb(255, 69, 0));
            viewTreeChildItem.StrNullColor = new SolidColorBrush(Color.FromRgb(255, 69, 0));
            viewTreeChildItem.StrKeyColor = new SolidColorBrush(Color.FromRgb(255, 69, 0));
            viewTreeChildItem.StrDefaultColor = new SolidColorBrush(Color.FromRgb(255, 69, 0));
            viewTreeChildItem.StrExtraColor = new SolidColorBrush(Color.FromRgb(255, 69, 0));
            viewTreeChildItem.StrCommentColor = new SolidColorBrush(Color.FromRgb(255, 69, 0));
        }

        /// <summary>
        ///     点击分析按钮后的载入效果
        /// </summary>
        /// <param name="isopen"></param>
        private void Loading(bool isopen)
        {
            ProgressLoading.Visibility = isopen ? Visibility.Visible : Visibility.Hidden;
            BtnSetting.IsEnabled = !isopen;
            BtnConnection.IsEnabled = !isopen;
        }


        /// <summary>
        ///     创建子节点的右键菜单
        /// </summary>
        /// <param name="mainDbSession"></param>
        /// <param name="slaveDbSession"></param>
        /// <param name="pos"></param>
        /// <param name="tableName"></param>
        /// <param name="fieldName"></param>
        /// <param name="childDiff"></param>
        /// <param name="notDiff"></param>
        /// <returns></returns>
        private ContextMenu ContextMenuChild(DbSession mainDbSession, DbSession slaveDbSession, int pos,
            string tableName, string fieldName, bool childDiff, bool notDiff)
        {
            var itemMenu = new ContextMenu();
            var menuItemCopy = Common.ContextMenuParentCreatItem(childDiff, pos, "复制字段到左边", "复制字段到右边",
                "ico_left.png",
                "ico_right.png");
            menuItemCopy.Click +=
                delegate { MenuItemChildCopy(mainDbSession, slaveDbSession, tableName, fieldName, notDiff); };
            itemMenu.Items.Add(menuItemCopy);
            itemMenu.Items.Add(new Separator());
            var menuItemDelete = Common.ContextMenuParentCreatItem("删除字段", "ico_delete.png");
            //menuItemDelete.Click += delegate { MenuItemChildDelete(mainDbSession, tableName, fieldName); };
            //itemMenu.Items.Add(menuItemDelete);
            return itemMenu;
        }


        /// <summary>
        ///     子节点菜单操作：复制到左/右边
        /// </summary>
        /// <param name="mainDbSession"></param>
        /// <param name="slaveDbSession"></param>
        /// <param name="tableName"></param>
        /// <param name="fieldName"></param>
        /// <param name="notDiff"></param>
        private async void MenuItemChildCopy(DbSession mainDbSession, DbSession slaveDbSession, string tableName,
            string fieldName, bool notDiff)
        {
            if (!notDiff)
            {
                Common.Msg(false, "请先在父节点进行 复制表 操作");
                return;
            }
            Loading(true);
            try
            {
                var rsTables =
                    mainDbSession.FromSql($"SHOW CREATE TABLE `{tableName}`").ToDataTable();
                var tableCreateStr = "";
                //先在主表中获取该表的DDL语句
                foreach (DataRow rsTablesRow in rsTables.Rows)
                    tableCreateStr = rsTablesRow[1].ToString();
                //如果查不到，则直接返回跳出
                if (string.IsNullOrEmpty(tableCreateStr)) return;
                //利用正则，查找该字段在DDL中的语句
                var regex = new Regex($"\\`{fieldName}\\`.*?,", RegexOptions.Singleline);
                var newStr = regex.Match(tableCreateStr).Value.TrimEnd(',');
                //查看副表是否有该字段
                var rsSlaveFields = slaveDbSession.FromSql($"DESC `{tableName}`").ToDataTable();
                var listFields = (from DataRow row in rsSlaveFields.Rows select row[0].ToString()).ToList();
                //如果副表有此字段，则直接进行更改操作
                if (listFields.Contains(fieldName))
                {
                    var sql = $"ALTER TABLE `{tableName}` CHANGE `{fieldName}` {newStr}";
                    slaveDbSession.ExecuteNonQuery(new MySqlCommand(sql));
                }
                else //如果副表无此字段
                {
                    //在主表在查询该表的所有字段信息
                    var rsMainFields = mainDbSession.FromSql($"DESC `{tableName}`").ToDataTable();
                    //获取该字段在主表中的位置索引
                    var index = 0;
                    for (var i = 0; i < rsMainFields.Rows.Count; i++)
                    {
                        if (rsMainFields.Rows[i][0].ToString() != fieldName) continue;
                        index = i;
                        break;
                    }
                    //拼装的SQL默认是把字段放在第一位
                    var parseSql = "FIRST";
                    //如果在主表中该字段不是在第一位，则进行查找前置字段操作
                    if (index > 0)
                    {
                        //此字段前置字段
                        var beforFields = rsMainFields.Rows[index - 1][0].ToString();
                        //如果副表没有此前置字段，则取副表最后个字段
                        if (!listFields.Contains(beforFields))
                            beforFields = listFields[listFields.Count - 1];
                        parseSql = $"AFTER `{beforFields}`";
                    }
                    var sql = $"ALTER TABLE `{tableName}` ADD COLUMN {newStr} {parseSql}";
                    slaveDbSession.ExecuteNonQuery(new MySqlCommand(sql));
                }
                var rs = await BindTreeView(TreeViewMain, TreeViewSlave, _mainDbSession, _slaveDbSession, tableName);
                if (rs)
                    Loading(false);
            }
            catch (Exception ex)
            {
                Loading(false);
                Common.Msg(false, $"出现意想不到的错误，信息：{ex.Message}");
            }
        }

        /// <summary>
        ///     子节点菜单操作：删除此字段
        /// </summary>
        /// <param name="mainDbSession"></param>
        /// <param name="tableName"></param>
        /// <param name="fieldName"></param>
        private async void MenuItemChildDelete(DbSession mainDbSession, string tableName, string fieldName)
        {
            var isSubmit = MessageBox.Show($"是否确定删除 {tableName} 的 {fieldName} 字段？", "提示", MessageBoxButton.YesNo,
                MessageBoxImage.Question, MessageBoxResult.No);
            if (isSubmit != MessageBoxResult.Yes) return;
            Loading(true);
            try
            {
                mainDbSession.ExecuteNonQuery(new MySqlCommand($"ALTER TABLE `{tableName}` DROP COLUMN `{fieldName}`"));
                var rs = await BindTreeView(TreeViewMain, TreeViewSlave, _mainDbSession, _slaveDbSession, tableName);
                if (rs)
                    Loading(false);
            }
            catch (Exception ex)
            {
                Loading(false);
                Common.Msg(false, $"出现意想不到的错误，信息：{ex.Message}");
            }
        }


        /// <summary>
        ///     创建父节点的右键菜单
        /// </summary>
        /// <param name="mainDbSession">主表数据库对象</param>
        /// <param name="slaveDbSession">副表数据库对象</param>
        /// <param name="pos">1=在左边，2=在右边</param>
        /// <param name="tableName">当前表名</param>
        /// <param name="notDiff"></param>
        /// <returns></returns>
        private ContextMenu ContextMenuParent(DbSession mainDbSession, DbSession slaveDbSession, int pos,
            string tableName,
            bool notDiff)
        {
            var itemMenu = new ContextMenu();
            var menuItemCopy = Common.ContextMenuParentCreatItem(notDiff, pos, "复制表到左边", "复制表到右边",
                "ico_left.png",
                "ico_right.png");
            menuItemCopy.Click += delegate { MenuItemCopy(mainDbSession, slaveDbSession, tableName); };
            itemMenu.Items.Add(menuItemCopy);
            itemMenu.Items.Add(new Separator());
            var menuItemDelete = Common.ContextMenuParentCreatItem("删除表", "ico_delete.png");
            //menuItemDelete.Click += delegate { MenuItemDelete(mainDbSession, tableName); };
            //itemMenu.Items.Add(menuItemDelete);
            return itemMenu;
        }


        /// <summary>
        ///     父节点菜单操作：删除此表
        /// </summary>
        /// <param name="mainDbSession"></param>
        /// <param name="tableName"></param>
        private async void MenuItemDelete(DbSession mainDbSession, string tableName)
        {
            var isSubmit = MessageBox.Show($"是否确定删除 {tableName} 表？", "提示", MessageBoxButton.YesNo,
                MessageBoxImage.Question, MessageBoxResult.No);
            if (isSubmit != MessageBoxResult.Yes) return;
            Loading(true);
            try
            {
                mainDbSession.ExecuteNonQuery(new MySqlCommand($"DROP TABLE `{tableName}`"));
                var rs = await BindTreeView(TreeViewMain, TreeViewSlave, _mainDbSession, _slaveDbSession, tableName);
                if (rs)
                    Loading(false);
            }
            catch (Exception ex)
            {
                Loading(false);
                Common.Msg(false, $"出现意想不到的错误，信息：{ex.Message}");
            }
        }

        /// <summary>
        ///     父节点菜单操作：复制到左/右边(只复制表)
        /// </summary>
        /// <param name="mainDbSession"></param>
        /// <param name="slaveDbSession"></param>
        /// <param name="tableName"></param>
        private async void MenuItemCopy(DbSession mainDbSession, DbSession slaveDbSession, string tableName)
        {
            Loading(true);
            try
            {
                var rsTables =
                    mainDbSession.FromSql($"SHOW CREATE TABLE `{tableName}`").ToDataTable();
                var tableCreateStr = "";
                foreach (DataRow rsTablesRow in rsTables.Rows)
                    tableCreateStr = rsTablesRow[1].ToString();
                if (!string.IsNullOrEmpty(tableCreateStr))
                {
                    slaveDbSession.ExecuteNonQuery(new MySqlCommand(tableCreateStr));
                    var rs = await BindTreeView(TreeViewMain, TreeViewSlave, _mainDbSession, _slaveDbSession, tableName);
                    if (rs)
                        Loading(false);
                }
            }
            catch (Exception ex)
            {
                Loading(false);
                Common.Msg(false, $"出现意想不到的错误，信息：{ex.Message}");
            }
        }
    }
}